import { Device, GatewayType } from "@/api/interface/iot";
import { addProduct, copyProduct, getProductList, removeProduct } from "@/api/modules/iot/product";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import OnlineStatus from "@/components/Sansan/OnlineStatus/OnlineStatus";
import SelectDeptList from "@/components/Sansan/SelectDeptList";
import { MessageType } from "@/enums/messageEnum";
import { RouterPath } from "@/enums/routerPath";
import { DeviceType, ProductStatusEnum } from "@/enums/statusEnum";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { AuthBtns } from "@/utils/constants";
import { dataFormat } from "@/utils/format";
import { confirm, showMsg, showTips } from "@/utils/util";
import { useRouter } from "vue-router";
import BasicDialog from "./components/basicInfo/detailDialog";
import SaveToProduct from "./components/SaveToProduct";
import notData from "@/assets/images/cube/link.png";
import "./product.scss";
export default defineComponent({
	name: "ProductList",
	setup() {
		const router = useRouter();
		const initParam = reactive<Device.ReqProduct>({});

		const dataCallback = (data: any) => {
			data.records.map((item: any) => {
				item.status = item.status + "";
				return item;
			});
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current || 1,
				pageSize: data.size
			};
		};

		const getTableList = async (params: any) => {
			return getProductList(params);
		};
		const buttonsList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			buttonsList.value = await useAuthButtons();
		});
		onActivated(() => {
			proTable.value.getTableList();
		});
		const addDialog = reactive<any>({
			title: "添加产品",
			visible: false
		});
		const clickBtn = async (fn: string, row: any) => {
			let selected: any[] = row.selectList || [row];
			switch (fn) {
				case "mod":
				case "details":
					if (selected.length != 1) {
						showMsg("请选择一条记录", MessageType.warning);
						return;
					}
					router.push({
						path: RouterPath.productDetail,
						query: { id: selected[0].id, type: selected[0].deviceType, menuId: AuthBtns.iotProduct }
					});
					break;
				case "add":
					detail.value = {};
					addDialog.visible = true;
					break;
				case "del":
					if (!selected.length) {
						showMsg("请选择要删除的数据", MessageType.warning);
						return;
					}
					confirm({ content: "删除后无法找回，确定删除当前选择的产品" }).then(flag => {
						flag && submitDel({ id: selected.map(item => item.id).join(",") });
					});
					break;
				case "copy":
					if (selected.length != 1) {
						showMsg("请选择一条要复制的产品记录", MessageType.warning);
						return;
					}
					copyProductDialog.visible = true;
					copyProductDialog.formData = JSON.parse(JSON.stringify(selected[0]));
					// copyProductDialog.formData.id = selected[0].model;
					break;
			}
		};

		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "model", label: "产品编码", search: { el: "input" } },
			{ prop: "name", label: "产品名称", search: { el: "input" } },
			// { prop: "status", label: "产品状态", search: { slot: {} } },
			{ prop: "deviceType", label: "产品类型", search: { slot: {} } },
			{ prop: "deptName", label: "所属分组", search: { slot: {} } },
			{ prop: "descript", label: "产品描述" },
			{ prop: "createTime", label: "创建时间", width: "180" },
			{ prop: "operation", label: "操作", fixed: "right", width: 130 }
		];

		const proTable = ref<any>();
		const detail = ref<any>({});
		const submitDel = async (dataInfo: any) => {
			let res = await removeProduct({ ...dataInfo });
			let ok = showTips(res.code, "删除产品");
			if (ok) {
				proTable.value.clearSelection();
				proTable.value.reset();
			}
		};
		const submitAdd = async () => {
			detail.value.name = detail.value.name || detail.value.model;
			let res = await addProduct({ ...detail.value });
			let ok = showTips(res.code, "添加产品");
			if (ok) {
				addDialog.visible = false;
				proTable.value.reset();
			}
		};
		const copyProductDialog = reactive<any>({
			visible: false,
			formData: {}
		});
		const submitCopyProduct = async (data: Device.ReqProduct) => {
			// let newProduct = { ...copyProductDialog.formData };
			// newProduct.model = data.productModel;
			// newProduct.name = data.productName;
			// delete newProduct.id;
			let { code } = await copyProduct(data);
			let ok = showTips(code, "复制产品");
			if (ok) {
				copyProductDialog.visible = false;
				proTable.value.getTableList();
			}
		};
		return () => {
			return (
				<div>
					<BasicDialog
						width="800px"
						title={addDialog.title}
						v-model:visible={addDialog.visible}
						detail={detail.value}
						onSubmit={() => submitAdd()}
					></BasicDialog>
					<SaveToProduct
						title="复制产品"
						v-model:visible={copyProductDialog.visible}
						formData={copyProductDialog.formData}
						onSubmit={(data: Device.ReqProduct) => submitCopyProduct(data)}
					></SaveToProduct>
					<ProTable
						ref={proTable}
						title={buttonsList.value.length ? "" : "产品管理"}
						columns={columns}
						requestApi={getTableList}
						initParam={initParam}
						dataCallback={dataCallback}
						searchCol={5}
						toolbar={["grid"]}
						viewType="grid"
						gridSpan={12}
					>
						{{
							"search-status": () => {
								return (
									<el-select v-model={initParam.status} style="width:100px">
										<el-option label="全部" value=""></el-option>
										<el-option label={ProductStatusEnum.DEPLOY_LABEL} value={ProductStatusEnum.DEPLOY}></el-option>
										<el-option label={ProductStatusEnum.DEVELOP_LABEL} value={ProductStatusEnum.DEVELOP}></el-option>
									</el-select>
								);
							},
							"search-deviceType": () => {
								return (
									<el-select v-model={initParam.deviceType} style="width:100px">
										<el-option label="全部" value=""></el-option>
										<el-option label="设备" value={GatewayType.Device}></el-option>
										<el-option label="软网关" value={GatewayType.SoftGateway}></el-option>
										<el-option label="网关设备" value={GatewayType.Gateway}></el-option>
									</el-select>
								);
							},
							"search-deptName": () => {
								return <SelectDeptList detail={initParam} appendChild onChange={val => (initParam.deptId = val.id)} />;
							},
							tableHeader: (scope: any) => {
								return buttonsList.value?.map((item: any) => {
									return (
										<el-button onClick={() => clickBtn(item.component, scope)} type={item.btnClass}>
											<i class={`iconfont ${item.icon}`}></i>
											{item.menuName}
										</el-button>
									);
								});
							},
							cardBody: (scope: any) => {
								return (
									<div class="product-card flex">
										{/* <div class="title flex justify-between">
												<el-link title="查看产品详情" type="primary" onClick={() => clickBtn("details", scope.row)}>
													<div class="master-title">{scope.row.name}</div>
												</el-link>
												<div class="time">{dataFormat("datetime", scope.row.createTime)}</div>
											</div> */}
										<div class="left ">
											<el-image class="img" src={scope.row.photo ? `/api/file/download/${scope.row.photo}` : notData} />
											<div class="title">{scope.row.name}</div>
										</div>
										<div class="body">
											<div class="flex mt-4">
												<div class="label">创建时间</div>
												<div class="text">{dataFormat("datetime", scope.row.createTime)}</div>
											</div>
											{/* <div class="flex">
													<div class="label">产品名称</div>
													<div class="text">{scope.row.name}</div>
												</div> */}
											<div class="flex">
												<div class="label">产品编码</div>
												<div class="text">{scope.row.model || "--"}</div>
											</div>
											<div class="flex">
												<div class="label">产品类型</div>
												<div class="text">{DeviceType[scope.row.deviceType]}</div>
											</div>
											<div class="flex">
												<div class="label">产品说明</div>
												<div class="text">{scope.row.description || "--"}</div>
											</div>
											<div class="flex">
												<div
													class="label text-blue-600 cursor-pointer"
													type="primary"
													onClick={() => clickBtn("details", scope.row)}
												>
													详情
													<i class="iconfont iconbx-right-arrow-alt ml-1"></i>
												</div>
												<div
													class="text text-red-600 cursor-pointer"
													type="danger"
													disabled={buttonsList.value.find((item: any) => item.path == "del") ? false : true}
													onClick={() => clickBtn("del", scope.row)}
												>
													删除
													<i class="iconfont icontrash-2 ml-1"></i>
												</div>
											</div>
										</div>
									</div>
								);
							},
							status: (scope: any) => {
								return (
									<OnlineStatus
										v-model={scope.row.status}
										onlineLabel={ProductStatusEnum.DEPLOY_LABEL}
										offlineLabel={ProductStatusEnum.DEVELOP_LABEL}
									/>
								);
							},
							model: (scope: any) => {
								return (
									<div class="truncate cursor-pointer primary-color" onClick={() => clickBtn("details", scope.row)}>
										{scope.row.model}
									</div>
								);
							},
							createTime: (scope: any) => {
								return dataFormat("datetime", scope.row.createTime);
							},
							operation: (scope: any) => {
								return (
									<>
										<el-link
											type="primary"
											link
											class="iconfont iconbx-file"
											onClick={() => {
												clickBtn("details", scope.row);
											}}
										>
											详情
										</el-link>
									</>
								);
							},
							empty: () => {
								return (
									<div>
										<Empty
											class="text-left leading-6"
											subtitle="产品是设备的集合，通常是一组具有相同功能定义的设备集合。例如，产品指同一个型号的产品，设备就是该型号下的某个设备。"
											btnText="创建产品"
											onClick={(scope: any) => {
												clickBtn("add", scope);
											}}
										/>
									</div>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
